package com.epadmin.finanse.dochody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.type.Type;

import com.ep.general.GeneralClassMdt;
import com.epadmin.finanse.Finanse;

public class DochodMdt extends GeneralClassMdt<Dochod> {

	public DochodMdt() {
		super(Dochod.class);
	}

	public List<Dochod> getList() {
		getSession().beginTransaction();
		Criteria crit = getSession().createCriteria(Dochod.class);
		crit.addOrder(Order.desc("data"));
		return list(crit);
	}

	@SuppressWarnings("unchecked")
	public List<Finanse> getListByMonth() {
		getSession().beginTransaction();
		
		Criteria crit = getSession().createCriteria(Dochod.class);
		crit.setProjection(Projections
				.projectionList()
				.add(Projections.sqlGroupProjection("MONTH({alias}.data) as month, {alias}.data as a_data", "month",
						new String[] { "month", "a_data" }, new Type[] { new org.hibernate.type.IntegerType(),
								new org.hibernate.type.DateType() })).add(Projections.sum("kwota")));
		crit.addOrder(Order.asc("data"));

		List<Finanse> result = new ArrayList<Finanse>();
		Finanse fn = new Finanse();

		List<Object[]> list = crit.list();
		getSession().getTransaction().commit();

		for (Object[] item : list) {
			fn = new Finanse();
			fn.setData((Date) item[1]);
			fn.setKwota((BigDecimal) item[2]);
			result.add(fn);
		}

		return result;
	}
}
